<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        title="入职办理列表"
        :breadCrumb="['人事', '人事管理', '入职办理']"
        :showBack="false"
      ></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <div style="display: flex">
            <a-select :options="options" v-model="keyWold" />
            <a-input-search
              @press-enter="search"
              @search="search"
              v-model="keyWoldValue"
              placeholder="请输入"
            />
          </div>
          <a-input-search
            @press-enter="search"
            @search="search"
            v-model="phoneData"
            placeholder="输入手机号码搜索"
          />
          <a-button @click="reset">重置</a-button>
        </a-space>
      </template>
      <template #right>
        <a-button
          type="primary"
          @click="
            router.push({
              name: 'AddNewemployee',
              query: {
                progress: 4
              }
            })
          "
          >添加新员工</a-button
        >
        <a-button type="outline" @click="importVisible = true">导入</a-button>
        <a-button type="outline" @click="exportSettingVisible = true"
          >导出</a-button
        >
        <a-dropdown
          @popup-visible-change="handleBatchVisible"
          v-model:popup-visible="showBatch"
          @select="handleBatch"
        >
          <a-button type="outline">批量操作</a-button>
          <template #content>
            <a-doption :value="3">签署劳动合同</a-doption>
            <a-doption :value="2">确认入职</a-doption>
            <a-doption :value="3">签署劳动合同</a-doption>
          </template>
        </a-dropdown>
      </template>
    </ConditionBox>
    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :title="item.ctlCnName"
        v-for="(item, index) in selectedHeader"
        :key="index"
        :data-index="item.ctlCode"
        :width="200"
        :sortable="{
          sortDirections: ['ascend', 'descend']
        }"
      >
        <template
          v-if="showCtlCodeArr.includes(item.ctlCode)"
          #cell="{ record }"
        >
          <ShowInfo :record="record" :ctlCode="item.ctlCode" />
        </template>
        <!-- <template
        v-if="exportHeaderList?.includes(item.ctlCode)"
        #cell="{ record, rowIndex }"
      >
        {{ item }}
        {{ record.ctlValue[rowIndex].ctlValue }}
      </template> -->
      </a-table-column>
      <a-table-column :width="100" title="方案审批" fixed="right">
        <template #cell="{ record }">
          <span
            :class="{
              'text-gray':
                record.onboardingStatus === 0 ||
                record.onboardingStatus === 1 ||
                record.onboardingStatus === 2,
              'text-blue': record.onboardingStatus === 3,
              'text-green': record.onboardingStatus === 4,
              'text-red': record.onboardingStatus === 5
            }"
          >
            {{
              record.onboardingStatus <= 1
                ? '未发起'
                : record.onboardingStatus === 2
                ? '待审核'
                : record.onboardingStatus === 3
                ? '审核中'
                : record.onboardingStatus === 4
                ? '已通过'
                : record.onboardingStatus === 5
                ? '已拒绝'
                : ''
            }}
          </span>
        </template>
      </a-table-column>
      <a-table-column :width="100" title="手续办理" fixed="right">
        <template #cell="{ record }">
          <span
            :class="{
              'text-gray':
                record.entryFormalitiesStatus === '待发起' ||
                record.entryFormalitiesStatus === '待进行',
              'text-blue': record.entryFormalitiesStatus === '进行中',
              'text-green': record.entryFormalitiesStatus === '已完成'
            }"
          >
            {{ record.entryFormalitiesStatus }}
          </span>
        </template>
      </a-table-column>
      <a-table-column :width="150" fixed="right">
        <template #title>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-tooltip content="编辑入职信息">
            <icon-font
              type="icon-edit"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>
          <a-tooltip content="更多功能">
            <a-dropdown
              @select="(value: number, e: Event, id: number) => moreItemControl(value, e, record)"
            >
              <icon-font
                type="icon-more-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="singleControl(record)"
              />
              <template #content>
                <a-doption :value="1" v-if="record.epStatus !== 2"
                  >{{
                    record.epStatus == 0
                      ? '创建入职手续'
                      : record.epStatus === 1
                      ? '配置入职手续'
                      : ''
                  }}
                </a-doption>
                <a-doption :value="2" v-if="record.onboardingStatus <= 1"
                  >入职方案审批</a-doption
                >
                <a-doption :value="2" v-else>查看审批详情</a-doption>
                <a-doption
                  :value="3"
                  v-if="
                    record.onboardingStatus === 4 && record.contractStatus < 10
                  "
                  >发起合同签署</a-doption
                >
                <!-- v-role="{ role: 'contract-signing' }" -->

                <a-doption :value="4">放弃入职</a-doption>
                <a-doption
                  :value="6"
                  v-if="
                    record.entryFormalitiesStatus !== '待发起' &&
                    record.entryFormalitiesStatus !== '待进行'
                  "
                  >查看手续详情</a-doption
                >
              </template>
            </a-dropdown>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>

  <FormHeaderControlSetting
    title="入职办理表头设置"
    v-model:visible="setting"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :orginHeaderList="orginHeaderList.headerListCode"
  >
  </FormHeaderControlSetting>
  <ExportControlSetting
    v-model:visible="exportSettingVisible"
    title="入职办理导出设置"
    :result-list="exportHeaderList"
    @headerSave="exportSave"
    :forbidList="exportyForbidList"
  >
  </ExportControlSetting>
  <ImportModal
    v-model:visible="importVisible"
    :func="isHeaderSetting"
    :forbidList="forbidList"
    @importSave="importSave"
    @importHeaderSave="importHeaderSave"
    title="入职办理导入"
  >
  </ImportModal>
  <a-modal v-model:visible="templateVisible" :width="800" @ok="templateOk">
    <template #title> 更换人员模板 </template>
    <a-input-search
      @press-enter="templateSearch"
      @search="templateSearch"
      v-model="templatekeyWoldValue"
      style="width: 200px; margin-bottom: 20px"
      placeholder="请输入"
    />
    <a-table
      @select="selectId"
      :columns="templateColumns"
      row-key="id"
      :data="templateData.data"
      :row-selection="{
        type: 'radio'
      }"
    />
  </a-modal>
  <ApproveSelectModal
    v-model:visible="approveVisible"
    :data="approveList"
    @selectProcess="selectProcess"
  />
</template>
<script setup lang="tsx">
import { Message } from '@arco-design/web-vue';
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';
import { useMenusStore } from '@/store';
import clonedeep from 'lodash.clonedeep';
import {
  GetOnboardingWords,
  OnboardingExcel,
  PutPersonnelid,
  EOabcdegiilmnnooprrtx,
  GetOnboarding,
  EditOnboardingNode,
  DelOnboarding,
  AddStaff,
  AddPositionManage,
  PostOnboardingWords,
  GetManual
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { ChangeHumanInductionState } from '@/apis/management/personnel/changeManagement/inductionManagement';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import { ExportHumanRosterList } from '@/apis/management/human/humanRoster';
import {
  GetEntryProcedureDetail,
  ChangeEntryApprovalStatus
} from '@/apis/management/human/humanChange/entry/index';
import {
  PutHeaderSetting,
  GetHeaderSetting,
  PostHeaderSetting
} from '@/apis/management/base/index';
import {
  GetWorkPlaceList,
  GetOrganizationList
} from '@/apis/management/organization/organizationManagement';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { useRouter } from 'vue-router';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import EntryTable from '../entryTable';
import { GetStaff } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { PersonnelListParams } from '@/apis/management/personnel/baseSetting/TransactionSetting/type';
import TableTurn, { type paramsType } from '@/components/TableTurn/index.vue';
import { Modal, Button } from '@arco-design/web-vue';
import ApproveSelectModal from './components/ApproveSelectModal.vue';
import { getProcessByAcronym } from '@/apis/approve/index';

const route = useRoute();
const menusStore = useMenusStore();

// 模糊查询参数
const options = reactive([
  { label: '名字', value: 'name' },
  { label: '职位', value: 'position' }
]);
// 模糊类型
const keyWold = ref('name');
// 模糊查询值
const keyWoldValue = ref(route.query.name);

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true
});
let tableRef = ref();
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

const templateId = ref(0);
const isSelectId = ref(0);
const templateVisible = ref(false);
const templatekeyWoldValue = ref('');
const templateData: any = reactive({ data: [] });
const templateColumns = [
  {
    title: '人员信息模板名称',
    dataIndex: 'name'
  },
  {
    title: '模板内容',
    dataIndex: 'remark'
  }
];
const selectId = (e: (number | string)[]) => {
  templateId.value = e[0] as number;
};
const templateSearch = async () => {
  const res2: any = await GetHumanTemplateList({
    pageSize: 1,
    pageNumber: -1,
    name: templatekeyWoldValue.value
  });
  templateData.data = res2.content;
};
const templateOk = async () => {
  if (templateId.value) {
    await PutPersonnelid({
      id: isSelectId.value,
      personnelId: templateId.value
    });
    isSelectId.value = 0;
    templateId.value = 0;
  } else {
    Message.error('请选择人员模板');
  }
};
const EntryNotice = (data: any) => {
  router.push({
    name: 'EntryNotice',
    query: { id: data.key }
  });
};
const tables = ref();
let exportSettingVisible = ref(false); // 导出弹出框
let importVisible = ref(false); // 导入弹出框
let forbidList: string[] = []; // 必选的表头
let exportHeaderList = ref(); // 接口获取过来的原始表头数据
const router = useRouter();
let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let headerSetting = ref<any>([]); // 当前的表头数据
let orginHeaderList = ref([]); // 原始的表头数据

const getTableData = async (params: paramsType) => {
  try {
    // keyWoldValue.value = keyWoldValue.value || route.query.name;
    const res = await GetStaff({
      ...params,
      typeName: '3,4',
      [keyWold.value]: keyWoldValue.value,
      mobile: phoneData.value
    });

    for (let item of res.content) {
      item.ctlValue.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
      // 判断入职手续办理状态的值
      const entryFormalitiesStatus = await handleEntryFormalitiesStatus(item);
      item.entryFormalitiesStatus = entryFormalitiesStatus;
    }
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 刷新列表
const refresh = (page?: any) => {
  tableRef.value.loadData();
};

// onMounted(() => {
//   if (route.query.name) {
//     nextTick(() => {
//       keyWoldValue.value = route.query.name;
//       keyWold.value = 'name';
//       setTimeout(() => {
//         tableRef.value.loadData();
//       }, 100);
//     });
//   }
// });
// watch(
//   () => route.query.name,
//   (newVal: string) => {
//     nextTick(() => {
//       keyWoldValue.value = newVal;
//       keyWold.value = 'name';
//       setTimeout(() => {
//         refresh();
//       }, 100);
//     });
//   },
//   {
//     immediate: true
//   }
// );

// 储存要特殊处理的数据
const showInfoData = reactive({
  data: {
    deptList: [], // 组织列表数据
    workPlaceList: [], // 工作地点数据
    positionList: [] // 职位列表数据
  }
});

// 新增表头
const addHeader = async () => {
  //SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB
  try {
    const {
      funcCtlInfos: { children }
    } = await GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    });

    let headerListCode: any = [];
    children?.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 4,
      headerListCode: headerListCode.join(',')
    });

    init();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 初始化数据
const init = async () => {
  const [
    headerSettingRes,
    businessModalDataRes,
    humanListRes,
    deptListRes,
    workPlaceListRes,
    positionListRes
  ] = await Promise.all([
    // 获取表头
    GetHeaderSetting({
      ownerFuncType: 4,
      userId: +(localStorage.getItem('userId') as string)
    }),
    // 控件数据
    GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    }),
    // 人员列表
    GetHumanTemplateList({
      pageNumber: 0,
      pageSize: -1
    }),
    // 组织列表
    GetOrganizationList({}),
    // 工作地点
    GetWorkPlaceList({
      pageNumber: 0,
      pageSize: -1
    }),
    GetPosition({
      pageNumber: 0,
      pageSize: -1
    })
  ]);

  orginHeaderList.value = headerSettingRes;
  headerSetting.value = [];
  const headerChildren = businessModalDataRes.funcCtlInfos.children;
  headerChildren.forEach((child: any, index: number) => {
    headerSetting.value.push({
      collectionName: child.subDetail.cnName,
      collectionCode: child.subDetail.subCode,
      heads: child.subDetail.subRelDetail.map((subDetail: any) => {
        const isDefault = headerSettingRes.headerListCode.includes(
          subDetail.ctlCode
        );
        return {
          ...subDetail,
          isDefault
        };
      })
    });
  });
  exportHeaderList.value = headerSetting.value;
  if (headerSettingRes.headerListCode.length < 1) {
    addHeader();
  }
  showInfoData.data.deptList = flatTree(dataTreeFilter(deptListRes));
  showInfoData.data.workPlaceList = workPlaceListRes.content;
  showInfoData.data.positionList = positionListRes.content;
};
init();

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'CE009C2E2B542409D815F0D3D54FE0E2B',
  'C2818BAA63AE848AA845DA2E81ECB1843'
];
// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 公司
    case 'CA8ABCC1480744557B3014C3454465A7E':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CA8ABCC1480744557B3014C3454465A7E']
            )?.name
          }
        </div>
      );
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 工作地点
    case 'CE009C2E2B542409D815F0D3D54FE0E2B':
      return (
        <div>
          {
            showInfoData.data.workPlaceList.find(
              (item: any) =>
                item.id == record['CE009C2E2B542409D815F0D3D54FE0E2B']
            )?.name
          }
        </div>
      );
    // 职位名称
    case 'C2818BAA63AE848AA845DA2E81ECB1843':
      return (
        <div>
          {
            showInfoData.data.positionList.find(
              (item: any) =>
                item.id == record['C2818BAA63AE848AA845DA2E81ECB1843']
            )?.name
          }
        </div>
      );
    default:
      break;
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将姓名移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});
// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 4,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 处理入职手续办理状态
const handleEntryFormalitiesStatus = async (record: any) => {
  try {
    if (record.epStatus !== 2) {
      return '待发起';
    } else if (record.epStatus === 2) {
      const { children } = await GetEntryProcedureDetail({
        id: record.id,
        type: 2
      });
      let totalCount = children.length;
      let finishCount = 0;
      let unFinishCount = 0;
      children.forEach((item: any) => {
        if (item.handlerEnter === 1 && item.createEnter === 1) {
          finishCount++;
        } else if (item.handlerEnter === 2 && item.createEnter === 2) {
          unFinishCount++;
        }
      });
      if (unFinishCount === totalCount) {
        return '待进行';
      } else if (finishCount === totalCount) {
        return '已完成';
      } else return '进行中';
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let showBatch = ref(false);
// 批量操作
const handleBatchVisible = () => {
  if (selectedList.value.length === 0) {
    Message.error('请先选择数据');
    showBatch.value = false;
    return;
  }
};

// 批量操作
const handleBatch = (key: number) => {
  isMoreSelect.value = true;
  switch (key) {
    case 3:
      moreItemControl(3, '签署劳动合同');
      break;
    case 2:
      moreItemControl(5, '确认入职');
      break;
    case 4:
      moreItemControl(4, '放弃入职');
      break;
    default:
      break;
  }
};

const ids = ref();
const goDetail = (data: any) => {
  console.log(111, data);
  router.push({
    name: 'EditTemplate',
    query: { id: data.id, node: 1 }
  });
};

let singleSelectId = 0; // 储存单个item移动、合并的id
let singleSelectData = {}; // 储存单个item移动、合并的值
let isMoreSelect = ref(false); // 判断是否批量
// 点击三个小点事件
const singleControl = (record: any) => {
  singleSelectData = record;
  singleSelectId = record.id;
  isMoreSelect.value = false;
};

// 表格中的三个小点按钮的下拉菜单
const moreItemControl = async (key: number, e: Event | string, id?: number) => {
  try {
    if (typeof e === 'string' && selectedList.value.length < 1) {
      Message.error('请至少选择一项!');
      return;
    }
    let title = e?.target?.innerText;
    let content: any;
    let onOk: (() => void) | undefined;
    // let title;
    switch (key) {
      case 1:
        router.push({
          name: 'Formalities',
          query: { id: singleSelectId }
        });
        break;
      case 2:
        getApproveList();
        approveVisible.value = true;
        selectedUserId.value = id.id;

        // 如果是未发起状态则暂时变成已通过状态，等待审批接入
        // if (singleSelectData.onboardingStatus <= 1) {
        //   await ChangeEntryApprovalStatus({
        //     id: singleSelectId,
        //     status: 4
        //   });
        //   refresh();
        // }
        // 查看审批详情
        // else {
        //
        // }

        // Message.info('等审批');
        // router.push({
        //   name: 'Formalities',
        //   query: { id: data.id }
        // });
        break;

      // 审批
      case 3:
        if (isMoreSelect.value) {
          const temp = selectedListData.value.findIndex(
            (el: any) => el.onboardingStatus !== 4
          );
          if (temp !== -1) {
            Message.error('请选择入职方案审批已通过状态的人员');
            return;
          } else {
            router.push({
              name: 'ContractWaitSigned'
            });
          }
        } else {
          router.push({
            name: 'ContractWaitSigned',
            query: {
              name: singleSelectData.name
            }
          });
        }
        menusStore.setMenuKey('7');
        menusStore.setCurrMenus('contract');
        break;
      // 放弃入职
      case 4:
        content = (
          <>
            <h3>是否确认放弃入职？</h3>
          </>
        );
        onOk = async () => {
          await ChangeHumanInductionState({
            ids: isMoreSelect.value ? selectedList.value : [singleSelectId],
            type: 8
          });
          refresh();
        };
        break;
      // 确认入职
      case 5:
        content = (
          <>
            <h3>是否确认入职？</h3>
          </>
        );
        onOk = async () => {
          if (isMoreSelect.value) {
            const temp = selectedListData.value.findIndex(
              (el: any) =>
                el.onboardingStatus !== 4 ||
                el.entryFormalitiesStatus !== '已完成'
            );
            console.log('====================================');
            console.log(temp);
            console.log('====================================');
            if (temp !== -1) {
              Message.error(
                '请选择入职方案审批已通过状态且入职手续办理已完成的人员'
              );
              return;
            }
          }
          await ChangeHumanInductionState({
            ids: isMoreSelect.value ? selectedList.value : [singleSelectId],
            type: 5
          });
          refresh();
        };
        break;
      // 查看入职手续详情
      case 6:
        router.push({
          name: 'EntryFormalitiesDetail',
          params: { id: singleSelectId }
        });
        break;
      default:
        break;
    }
    if (key !== 1 && key !== 2 && key !== 3 && key !== 6)
      Modal.open({
        title,
        content,
        onOk
      });
  } catch (error: unknown) {
    console.log(error);
  }
};
// 跳转新增员工页面
const add = () => {
  router.push({
    name: 'AddNewemployee',
    query: { id: 1 }
  });
};

// 删除入职信息
const del = async (id: number) => {
  await DelOnboarding({ ids: [id] });
  init();
};
// 是否显示表头
const isHeaderSetting = async () => {
  try {
    setting.value = !setting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};
const phoneData = ref('');
const search = () => {
  refresh();
};

let exportyForbidList = [
  'C30BBF36A5AF541F7A2657671DEE2EDD6', // 组织名称
  'CB1AAC9E508714223BA4D1596FE690877', // 组织编码
  'C3D33FA57216F4968BDE51C31D623FC09', // 组织类型
  'CD25749DBA68E4BF3BCA616DD63751CB7', // 编制人数
  'CB0C63F38283045F58FFF1B1EABE5D151', // 组织负责人
  'CE009C2E2B542409D815F0D3D54FE0E2B' // 工作地点
]; // 必选的表头
const exportSave = async (used: any) => {
  try {
    if (!ids.value || ids.value.length === 0) {
      Message.error('请至少选择一项导出！');
      return;
    } else {
      let code: any = [],
        name: any = [];
      used.forEach((item: any) => {
        code.push(item.code);
        name.push(item.name);
      });

      const formData = new FormData();
      formData.append('ctlCodes', code + '');
      formData.append('ctlCnNames', name + '');
      formData.append('ids', ids.value + '');
      const res = await OnboardingExcel(formData);

      if (ids.value?.length === 1) {
        downloadExcelFile(
          res,
          `${tables.value.selectedListData.data[0]['C62B8DC31189847E0972B5D8F721404B1']}信息导出`
        );
      } else {
        downloadExcelFile(
          res,
          `${tables.value.selectedListData.data[0]['C62B8DC31189847E0972B5D8F721404B1']}等信息导出`
        );
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 下载导入模板
const importHeaderSave = async (used: any, userId: number) => {
  try {
    // let excels: any = [];
    let code: any = [],
      name: any = [],
      necessary: any = [];
    used.forEach((item: any) => {
      code.push(item.code);
      name.push(item.name);
      if (forbidList?.includes(item.code)) necessary.push('true');
      else necessary.push('false');
    });
    const formData = new FormData();
    formData.append('code', code + '');
    formData.append('name', name + '');
    formData.append('necessary', necessary + '');
    // const res = await PostImportTemplate(formData);
    // downloadExcelFile(res, '员工花名册导入模板');
  } catch (error: unknown) {
    console.log(error);
  }
};

const importSave = async (file: any) => {
  try {
    let formData = new FormData();
    formData.append('data', file.file);
    console.log(formData);

    await EOabcdegiilmnnooprrtx(formData);
  } catch (error: unknown) {
    console.log(error);
  }
};
// 重置数据
const reset = () => {
  keyWold.value = 'name';
  keyWoldValue.value = '';
  phoneData.value = '';
  refresh();
};
const approveVisible = ref(false);
const approveList = ref([]); //流程列表
/**
 * 获取流程列表
 */
const getApproveList = async () => {
  if (approveList.value.length) return;
  const res = await getProcessByAcronym('onboarding_plan');
  approveList.value = res?.list || [];
};
const selectedUserId = ref(0); //选中的用户
/**
 * 发起入职审批
 */
const selectProcess = (processId: number) => {
  if (!processId) return;
  router.push({
    name: 'InitiateApproval',
    query: { processId, userId: selectedUserId.value }
  });
};
</script>
<style lang="less" scoped>
.wrap {
  padding: 10px 20px;

  // 弄出一个小的圆形
}
</style>
